package com.demo.practiceui.views.interactive;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 滑动解锁控件
 * 核心知识点：
 * 1. onTouchEvent - 处理触摸事件
 * 2. MotionEvent.ACTION_DOWN/MOVE/UP - 触摸事件类型
 * 3. 边界判断和滑动限制
 * 4. 回调接口 - 通知解锁成功
 */
public class SlideUnlockView extends View {

    // 滑块位置
    private float sliderX = 0;
    private float sliderY = 0;
    private float sliderRadius = 60f;

    // 尺寸
    private int width;
    private int height;
    private float trackHeight = 120f;
    private float cornerRadius = 60f;

    // 状态
    private boolean isUnlocked = false;
    private boolean isDragging = false;

    // 画笔
    private Paint trackPaint;       // 轨道画笔
    private Paint sliderPaint;      // 滑块画笔
    private Paint textPaint;        // 文字画笔
    private Paint arrowPaint;       // 箭头画笔

    // 触摸相关
    private float touchDownX;

    // 回调接口
    private OnUnlockListener onUnlockListener;

    public interface OnUnlockListener {
        void onUnlock();
    }

    public SlideUnlockView(Context context) {
        this(context, null);
    }

    public SlideUnlockView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideUnlockView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 轨道画笔
        trackPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        trackPaint.setColor(Color.parseColor("#E0E0E0"));
        trackPaint.setStyle(Paint.Style.FILL);

        // 滑块画笔
        sliderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        sliderPaint.setColor(Color.parseColor("#4CAF50"));
        sliderPaint.setStyle(Paint.Style.FILL);
        sliderPaint.setShadowLayer(15, 0, 5, Color.parseColor("#80000000"));

        // 文字画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.parseColor("#999999"));
        textPaint.setTextSize(36f);
        textPaint.setTextAlign(Paint.Align.CENTER);

        // 箭头画笔
        arrowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        arrowPaint.setColor(Color.WHITE);
        arrowPaint.setStyle(Paint.Style.STROKE);
        arrowPaint.setStrokeWidth(8f);
        arrowPaint.setStrokeCap(Paint.Cap.ROUND);
        arrowPaint.setStrokeJoin(Paint.Join.ROUND);

        setLayerType(LAYER_TYPE_SOFTWARE, null);  // 开启阴影
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 800;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 200;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        sliderY = height / 2f;
        
        if (sliderX == 0) {
            sliderX = sliderRadius + 20;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isUnlocked) {
            drawUnlockedState(canvas);
        } else {
            drawNormalState(canvas);
        }
    }

    /**
     * 绘制正常状态（未解锁）
     */
    private void drawNormalState(Canvas canvas) {
        // 测试：绘制整个View的背景（用于验证View是否被拉伸）
        // 如果View被拉伸，这个红色背景会填满整个高度
        Paint testPaint = new Paint();
        testPaint.setColor(Color.parseColor("#33FF0000"));  // 半透明红色
        canvas.drawRect(0, 0, width, height, testPaint);
        
        float trackTop = (height - trackHeight) / 2;
        float trackBottom = trackTop + trackHeight;

        // 1. 绘制轨道背景
        RectF trackRect = new RectF(20, trackTop, width - 20, trackBottom);
        canvas.drawRoundRect(trackRect, cornerRadius, cornerRadius, trackPaint);

        // 2. 绘制提示文字
        if (!isDragging) {
            textPaint.setColor(Color.parseColor("#999999"));
            canvas.drawText("滑动解锁 >>", width / 2f, height / 2f + 12, textPaint);
        } else {
            // 根据滑动进度改变文字透明度
            float progress = (sliderX - sliderRadius - 20) / (width - 2 * sliderRadius - 40);
            int alpha = (int) (255 * (1 - progress));
            textPaint.setColor(Color.argb(alpha, 153, 153, 153));
            canvas.drawText("继续滑动 >>", width / 2f, height / 2f + 12, textPaint);
        }

        // 3. 绘制滑块
        canvas.drawCircle(sliderX, sliderY, sliderRadius, sliderPaint);

        // 4. 绘制滑块上的箭头
        drawArrows(canvas, sliderX, sliderY);
    }

    /**
     * 绘制解锁成功状态
     */
    private void drawUnlockedState(Canvas canvas) {
        float trackTop = (height - trackHeight) / 2;
        float trackBottom = trackTop + trackHeight;

        // 绘制绿色背景
        trackPaint.setColor(Color.parseColor("#4CAF50"));
        RectF trackRect = new RectF(20, trackTop, width - 20, trackBottom);
        canvas.drawRoundRect(trackRect, cornerRadius, cornerRadius, trackPaint);

        // 绘制成功文字
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(42f);
        canvas.drawText("解锁成功 ✓", width / 2f, height / 2f + 14, textPaint);
    }

    /**
     * 绘制滑块上的箭头
     */
    private void drawArrows(Canvas canvas, float x, float y) {
        float arrowSize = 20f;
        float spacing = 15f;

        // 绘制两个箭头
        for (int i = 0; i < 2; i++) {
            float offsetX = -arrowSize + i * spacing;
            
            // 箭头线段
            canvas.drawLine(x + offsetX, y - arrowSize / 2,
                    x + offsetX + arrowSize, y, arrowPaint);
            canvas.drawLine(x + offsetX, y + arrowSize / 2,
                    x + offsetX + arrowSize, y, arrowPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isUnlocked) {
            return true;  // 已解锁，不处理触摸事件
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 判断是否点击在滑块上
                float touchX = event.getX();
                float touchY = event.getY();
                float distance = (float) Math.sqrt(Math.pow(touchX - sliderX, 2) + Math.pow(touchY - sliderY, 2));
                
                if (distance <= sliderRadius) {
                    isDragging = true;
                    touchDownX = touchX;
                    // 告诉父容器（如 ViewPager2）不要拦截此次触摸，避免左右滑到下一页
                    if (getParent() != null) {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                    return true;
                }
                break;

            case MotionEvent.ACTION_MOVE:
                if (isDragging) {
                    float newX = event.getX();
                    
                    // 限制滑块在轨道范围内
                    float minX = sliderRadius + 20;
                    float maxX = width - sliderRadius - 20;
                    sliderX = Math.max(minX, Math.min(maxX, newX));
                    // 拖拽过程中持续请求父容器不拦截
                    if (getParent() != null) {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                    
                    invalidate();
                    return true;
                }
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (isDragging) {
                    isDragging = false;
                    // 手势结束，允许父容器恢复拦截
                    if (getParent() != null) {
                        getParent().requestDisallowInterceptTouchEvent(false);
                    }
                    
                    // 判断是否滑动到最右边
                    float threshold = width - sliderRadius - 50;
                    if (sliderX >= threshold) {
                        // 解锁成功
                        isUnlocked = true;
                        if (onUnlockListener != null) {
                            onUnlockListener.onUnlock();
                        }
                    } else {
                        // 回弹动画
                        animateSliderBack();

                    }
                    
                    invalidate();
                    return true;
                }
                break;
        }

        return super.onTouchEvent(event);
    }

    /**
     * 滑块回弹动画
     */
    private void animateSliderBack() {
        ValueAnimator animator = ValueAnimator.ofFloat(sliderX, sliderRadius + 20);
        animator.setDuration(300);
        animator.addUpdateListener(animation -> {
            sliderX = (float) animation.getAnimatedValue();
            invalidate();
        });
        animator.start();
    }

    /**
     * 重置解锁状态
     */
    public void reset() {
        isUnlocked = false;
        sliderX = sliderRadius + 20;
        trackPaint.setColor(Color.parseColor("#E0E0E0"));
        textPaint.setTextSize(36f);
        invalidate();
    }

    /**
     * 设置解锁监听器
     */
    public void setOnUnlockListener(OnUnlockListener listener) {
        this.onUnlockListener = listener;
    }
}

